package http.mapping;

import http.executor.ResponseExecutor;
import http.executor.Task;
import http.method.support.HandlerMethodArgumentResolver;
import http.method.support.MethodParameter;
import http.method.support.RequestParamMapMethodArgumentResolver;
import http.thread.FutureService;
import http.util.ParamUtil;
import http.util.ReflectionUtil;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpRequest;
import java.lang.reflect.Method;
import java.util.*;

public class InvocableHandlerMethod implements FutureService {
    private static InvocableHandlerMethod instance=new InvocableHandlerMethod();

    private static HandlerMethodArgumentResolver resolver=new RequestParamMapMethodArgumentResolver();

    public static InvocableHandlerMethod getInstance() {
        return instance;
    }

    public static Object invokeForRequest(HandlerMethod handlerMethod) throws Exception {
        System.out.println("处理任务的thread:"+Thread.currentThread());
        Method method = handlerMethod.getMethod();
        MethodParameter[] parameters = handlerMethod.getParameters();
        Object[] args= new Object[parameters.length];
        FullHttpRequest req = handlerMethod.getReq();
        Map<String, Object> reqParam=ParamUtil.getParamsMap(req);
        Map<String, Object> initModel=ParamUtil.getParamsMap(req);

        List<Object> wrapperList=new ArrayList<>();
        for (int i = 0; i < parameters.length; i++) {
            if(resolver.supportsParameter(parameters[i])){
                parameters[i].setReqParam(reqParam);
                args[i]=resolver.resolveArgument(req,parameters[i]);

                if(parameters[i].isWrapperBean()){
                    wrapperList.add(args[i]);
                }
                initModel.put(parameters[i].getParameterName(),args[i]);
            }
        }
        //填充model
        for (Object obj : wrapperList) {
              ReflectionUtil.mapFillPojo(initModel,obj);
        }

        return method.invoke(handlerMethod.getBean(),args);
    }


    @Override
    public Object handler(Object... args) throws Exception{
        if(args == null || args.length == 0 || !(args[0] instanceof Task)){
            throw new RuntimeException("参数不合法args："+Arrays.toString(args));
        }
        Task task= (Task) args[0];
        return this.invokeForRequest(task.getHandle());
    }

    @Override
    public void onSuccess(Object result, Object... args) {
        Task task= (Task) args[0];
        ResponseExecutor.putResult(task.getId(),result);
    }

    @Override
    public void onFailure(Throwable throwable, Object... args) {
        Task task= (Task) args[0];
        ResponseExecutor.putResult(task.getId(),throwable);
    }
}
